﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Speech.Synthesis;
using Infragistics.Win.UltraMessageBox;
using KD.Sms.Card;
using KD.Sms.Entity;

namespace KD.Sms
{
    public partial class frmDebug : Form
    {
        public frmDebug()
        {
            InitializeComponent();
        }

        SerialClass obj = null;
        private void frmDebug_Load(object sender, EventArgs e)
        {
            CacheMemoryCenter.M_CurrentMsgBox = richTextBox1;
            //decimal d = Convert.ToDecimal("1.68");
            //MessageBox.Show((d + Convert.ToDecimal("0.06")).ToString());
            ////CacheSamplingPacking.DoInit();
            ////Entity.SamplingInfoForPailSave model = new Entity.SamplingInfoForPailSave();
            ////model.E_SamplingPail = 2;
            ////model.E_SamplingPoscount = 3;
            ////CacheSamplingPacking.E_PackingSaveValueSet = model;
            ////model = new Entity.SamplingInfoForPailSave();
            ////model.E_SamplingPail = 3;
            ////model.E_SamplingPoscount = 4;
            ////CacheSamplingPacking.E_PackingSaveValueSet = model;
            //MessageBox.Show(CacheSamplingPacking.DoGetCachePointCount().ToString());
            //return;
            //CacheMemoryCenter.M_CurrentMsgBox = richTextBox1;
            //obj = new SerialClass("COM8");
            //obj.DataReceived += new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);
            ////MessageBox.Show(DAL.SqlLite.Main.Instance.DoQueryCodes(DateTime.Now));
            ////MessageBox.Show(DAL.SqlLite.Main.Instance.DoQueryCodes(DateTime.Now.AddDays(2)));
            //return;
            //初始化样桶读卡对象
            E_Rfid = new Card.Stm32Main();
            ActionCenter.Action.Instance.ReadCardStm32 += OnReadCardStm32;
            return;
            //string _strRFID = "E2-80-11-05-20-00-79-9A-9C-9C-08-C7";
            //UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, _strRFID.ToUpper().Replace("-", "").Substring(8, 16));

            //ActionCenter.Action.Instance.CarNumChanged += OnCarNumChanged;
        }
        private void OnCarNumChanged(object sender, ActionCenter.CommonEventArgs e)
        {
            MessageBox.Show(e.E_Values.ToString());
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //if (DAL.DAS.Main.Instance.DoSubmitSamplingBegin("南侧采样机", "230306084640918", 9, 8, 7, 6, "1,0,112,112,112*2,1,113,113,113*3,2,114,114,114*"))
            //    MessageBox.Show("Successfull!");
            //else
            //    MessageBox.Show("Failure!");
        }



        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            //DAL.SqlLite.Main.Instance.DoGetPailForSampling("123123", 4, 2);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Share.SamplingPosGen samplingPosGen = new Share.SamplingPosGen(100, 1000, 100, 500, 100, 0, 0);
            List<Entity.SamplingPos> _list = samplingPosGen.MakeSamplingPos(8, SamplingPosMakeType.KD_3PartRand);
            //ActionCenter.Action.Instance.E_SamplingPos = E_CrrentArrySamplingPos;
            richTextBox1.Clear();
            foreach (Entity.SamplingPos _blcok in _list)
            {
                richTextBox1.AppendText("\r\n" + _blcok.BlockNumber.ToString() + "\t" + _blcok.XBegin.ToString() + "\t" + _blcok.XEnd.ToString() + "\t" + _blcok.X.ToString() + "\t" + _blcok.YBegin.ToString() + "\t" + _blcok.YEnd.ToString() + "\t" + _blcok.Y.ToString() + "\t");
            }
            //SamplingPos _blcok;
            //richTextBox1.AppendText("\r\n块号\tX起点\tX终点\tX值\tY起点\tY终点\tY值\t");
            //for (int i = 1; i <= 36; i++)
            //{
            //    _blcok = _obj.GetBlock(i);
            //}
        }

        private void button8_Click(object sender, EventArgs e)
        {

        }




        private void button9_Click(object sender, EventArgs e)
        {
            ActionCenter.Action.Instance.ReadCardStm32 += DoReadCardStm32;
            Card.Stm32Main.Instance.DoRead("192.168.2.209", 5000, false);
        }

        private void DoReadCardStm32(object sender, ActionCenter.CommonEventArgs e)
        {
            Entity.StmResult model = (Entity.StmResult)e.E_Values;
            UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, model.E_Success.ToString());
            UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, model.E_Desc);
            UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, model.E_ReadBegin.ToString("HH:mm:ss"));
            UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, model.E_ReadEnd.ToString("HH:mm:ss"));
            if (model.E_Cards != null && model.E_Cards.Count > 0)
            {
                foreach (CardInfo str in model.E_Cards)
                {
                    UI.FormHelper.RicMsgShow(richTextBox2, UI.MsgType.Error, str.E_Tid + "\r\t" + str.E_Count);
                }
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            SerialServer.PLY650_Net obj = new SerialServer.PLY650_Net("192.168.2.24", 26);
            obj.ReadEvent += OnReadEvent;
            obj.DoRead();
        }

        private void OnReadEvent(object sender, SerialServer.CommonEventArgs e)
        {
            UI.FormHelper.RicMsgShow(richTextBox1, UI.MsgType.Error, e.M_Value.ToString());
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button11_Click(object sender, EventArgs e)
        {
            string phrase = richTextBox1.Text;// "123我是好人";
            Voicer.Instance.DoSendSound(phrase);
            return;
            SpeechSynthesizer speech = new SpeechSynthesizer();
            CultureInfo keyboardCulture = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
            InstalledVoice neededVoice = speech.GetInstalledVoices(keyboardCulture).FirstOrDefault();
            if (neededVoice == null)
            {

                phrase = "Unsupported Language";
            }
            else if (!neededVoice.Enabled)
            {
                phrase = "Voice Disabled";
            }
            else
            {
                speech.SelectVoice(comboBox1.Text);
            }

            speech.Speak(phrase);
        }

        private void DoSend()
        {
        }

        private void button12_Click(object sender, EventArgs e)
        {
            SpeechSynthesizer speech = new SpeechSynthesizer();
            CultureInfo keyboardCulture = System.Windows.Forms.InputLanguage.CurrentInputLanguage.Culture;
            foreach (InstalledVoice neededVoice in speech.GetInstalledVoices(keyboardCulture))
            {
                comboBox1.Items.Add(neededVoice.VoiceInfo.Name);
            }
        }


        Image E_CurrentImage = null;

        private void button13_Click(object sender, EventArgs e)
        {
            LiveShow.DoCatchImage(ref E_CurrentImage, "", false, false);
            if (E_CurrentImage != null)
            {
                DoDrawString(E_CurrentImage, "测试");
            }
        }
        /// <summary>
        /// 往图片绘制文字
        /// </summary>
        /// <param name="img"></param>
        /// <param name="str"></param>
        private Image DoDrawString(Image img, string str)
        {
            if (img != null)
            {
                Graphics g = Graphics.FromImage(img);
                Font font = new Font("宋体", 16, FontStyle.Bold);
                SolidBrush sbrush = new SolidBrush(Color.Red);
                g.DrawString(str, font, sbrush, new PointF(10, 10));
            }
            return img;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button14_Click(object sender, EventArgs e)
        {
            LiveShow.DoConnect("192.168.2.27", 8000, "admin", "qwer1234!@#$", 1);
            LiveShow.E_Enable = true;
        }

        Card.Stm32Main E_Rfid = null;
        private void button15_Click(object sender, EventArgs e)
        {
            CacheMemoryCenter.M_CurrentMsgBox = richTextBox1;
            E_Rfid.DoRead("192.168.2.12", 5000, false);
        }


        /// <summary>
        /// 读卡器异步事件
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnReadCardStm32(object send, ActionCenter.CommonEventArgs e)
        {
            Entity.StmResult _model = (Entity.StmResult)e.E_Values;
            if (_model != null)
            {
                if (_model.E_Success)
                {
                    if (_model.E_Cards != null)
                    {
                        if (_model.E_Cards.Count == 1)
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡成功!识别到卡号{0}!", _model.E_Cards[0].E_Tid));
                        }
                        else
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("读卡失败!系统成功读取到{0}张卡片!", _model.E_Cards.Count));
                            foreach (CardInfo tid in _model.E_Cards)
                            {
                                FormHelper.ApplicationShow(UI.MsgType.Error, tid.E_Tid + "\r\t" + tid.E_Count);
                            }
                        }
                    }
                }
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, "读卡失败!建议检查读卡器是否正常!");
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            MessageBox.Show(comboBox1.Text.Trim());
        }

        private void button16_Click(object sender, EventArgs e)
        {
            DAL.SqlLite.Main.Instance.DoSaveDataLocal("湘BH6711", "A9C3C75C", (decimal)25.5, (decimal)2.5, 15,
                                   (decimal)2.5, (decimal)1.75, "", "瘦煤", "安格鲁二瘦煤1", "唐山海港创能贸易有限2公司", "其它");
            DAL.SqlLite.Main.Instance.DoSaveDataLocal("冀BH6711", "A9C3C75C", (decimal)25.5, (decimal)2.5, 15,
                           (decimal)2.5, (decimal)1.75, "", "瘦煤", "安格鲁二瘦煤2", "唐山海港创能贸易有限2公司", "其它");
        }

        private void button17_Click(object sender, EventArgs e)
        {
            CacheMemoryCenter.M_CurrentMsgBox = richTextBox1;
            UI_Operate.DataUpload.E_NeedUpload = true;
            UI_Operate.DataUpload.DoStart();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            Byte[] _bySendStart = new Byte[8];
            _bySendStart[0] = 0x01;
            _bySendStart[1] = 0x03;
            _bySendStart[2] = 0x10;
            _bySendStart[3] = 0x00;
            _bySendStart[4] = 0x00;
            _bySendStart[5] = 0x01;
            _bySendStart[6] = 0x80;
            _bySendStart[7] = 0xca;
            obj.SendData(_bySendStart, 0, 8);
        }




        private void button19_Click(object sender, EventArgs e)
        {
            DoJudgeWaste();
            return;
        }


        /// <summary>
        /// 判断当前是否需要弃料
        /// </summary>
        /// <returns></returns>
        System.Data.DataTable _tabWaste;
        int _iWasteSet = 0, _iWasteCurrent = 0;
        List<string> _listWasteWaring = null;

        private void button20_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(DoTest)) { IsBackground = true };
            th.Start();
        }

        public void DoTest()
        {
            Random ro = new Random();
            int _iStep = 0;
            int _iXBegin, _xEnd, _iYBegin, _YEnd;
            List<SamplingPos> _list;
            while (_iStep < 5000)
            {
                _iXBegin = ro.Next(100, 120);
                _xEnd = ro.Next(260, 330);
                _iYBegin = ro.Next(100, 120);
                _YEnd = ro.Next(260, 330);
                Share.SamplingPosGen samplingPosGen = new Share.SamplingPosGen(_iXBegin, _xEnd, _iYBegin, _YEnd, ro.Next(134, 146), 0, 0);
                _list = samplingPosGen.MakeSamplingPos(3, SamplingPosMakeType.KD_3PartRand);
                if (DAL.SqlLite.Main.Instance.DoInsertSamplingPosForTest(_list))
                {
                    UI.FormHelper.SetControlText(label2, _iStep.ToString());
                    _iStep++;
                }
            }

        }

        SerialClass objCom;
        private void button21_Click(object sender, EventArgs e)
        {
            objCom = new SerialClass("COM3");
            objCom.DataReceived += new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);
        }

        public void sc_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e, byte[] bits)
        {
            try
            {
                string _strReadData = "Code:";
                string _strResult = "Result:";
                if (bits != null && bits.Length > 0)
                {
                    for (int i = 0; i < bits.Length; i++)
                    {
                        _strReadData = _strReadData + bits[i].ToString("X").PadLeft(2, '0') + " ";
                        if (i < bits.Length - 2)
                            _strResult = _strResult + (Convert.ToInt32(bits[i].ToString("X").PadLeft(2, '0')) - 30).ToString() + " ";
                    }
                }
                FormHelper.ApplicationShow(UI.MsgType.Error, _strReadData);
                FormHelper.ApplicationShow(UI.MsgType.Error, _strResult);
            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, ex.ToString());
            }
        }


        private void frmDebug_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                objCom.closePort();
            }
            catch { }
        }

        private void button22_Click(object sender, EventArgs e)
        {
 

            //var _textModel = DAL.SqlLite.Main.Instance.GetTestCarInfo("冀BC5982D");
            // XB: 122  XE: 274 YB: 595 YE: 172
            Share.SamplingPosGen samplingPosGen = new Share.SamplingPosGen(122, 274, 595, 172, DoCalculatedHeight(1.4), 0, 0);
             var pos = samplingPosGen.MakeSamplingPos(3, SamplingPosMakeType.KD_3PartRand);
        }

        /// <summary>
        /// 计算当前车辆采样深度 厘米转换脉冲
        /// </summary>
        /// <param name="_iCarHeight"></param>
        /// <returns></returns>
        private int DoCalculatedHeight(double _iCarHeight)
        {
            //double _deepScale = ((double)5090 - (double)1392) / ((double)146 - (double)100);
            //if (CacheMemoryCenter.E_IsDebug)
            //    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("脉冲系数:{0}", _deepScale));
            //double _deep = 146 - (_iCarHeight * 1000 - 1392 + 50) / _deepScale;
            //if (CacheMemoryCenter.E_IsDebug)
            //    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("计算深度脉冲:{0}", _deep));
            //return Convert.ToInt32(Math.Floor(_deep));
            double _deep = 146 - (_iCarHeight * 1000 - 1392 + 50) / 80;
            return Convert.ToInt32(Math.Floor(_deep));
        }

        private void DoJudgeWaste()
        {
            _tabWaste = DAL.SqlLite.Main.Instance.DoQueryWasteWaringJudgeParms();
            if (_tabWaste != null && _tabWaste.Rows.Count == 1)
            {
                _iWasteSet = int.Parse(_tabWaste.Rows[0]["WasteCount"].ToString());
                _iWasteCurrent = int.Parse(_tabWaste.Rows[0]["WasteCurrent"].ToString());
                if (_iWasteCurrent >= _iWasteSet)
                {
                    _listWasteWaring = new List<string>();
                    _listWasteWaring.Add("1、当前为弃料告警，提醒采样员关注弃料仓是否已满;");
                    _listWasteWaring.Add(string.Format("2、系统当前设置采样【{0}】车后开始关注弃料仓;", _iWasteSet));
                    _listWasteWaring.Add(string.Format("3、系统当前已成功采样【{0}】车;", _iWasteSet));
                    _listWasteWaring.Add("4、弃料完成后，点击菜单【辅助告警[O]】-【弃料完成[C]】解除报警;");
                    _listWasteWaring.Add("5、若报警阈值与实际偏差较大，可适当调整阈值;");

                }

                UltraMessageBoxInfo info = new UltraMessageBoxInfo();
                info.Header = "系统告警：请仔细阅读当前提示信息";
                info.Caption = "系统告警";
                info.Buttons = MessageBoxButtons.OK;
                foreach (string str in _listWasteWaring)
                {
                    info.Text += str + "\r\n";
                    info.Text += str + "\r\n";
                }
                Msg.ShowMessageBox(info);
            }
        }


    }
}
